package com.getpebble.android.main.sections.appstore.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.framework.fragment.IHandleBackPress;
import com.getpebble.android.common.framework.fragment.PblBaseFragment;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.FrameworkState.EventType;
import com.getpebble.android.common.model.LockerApp;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.framework.FrameworkEventReceiver;
import com.getpebble.android.framework.FrameworkEventReceiver.IFrameworkEventListener;
import com.getpebble.android.framework.PblFrameworkInterface;
import com.getpebble.android.framework.endpoint.InstallAppEndpoint.AppInstallResult;
import com.getpebble.android.jsbridge.JsBridgeUtil;
import com.getpebble.android.jsbridge.JsBridgeWebClient;
import com.getpebble.android.main.activity.MainActivity;
import com.getpebble.android.main.sections.appstore.constants.AppStoreConstants;
import com.getpebble.android.main.sections.appstore.constants.AppStoreConstants.StoreType;
import com.getpebble.android.util.HttpUtils;
import com.getpebble.android.webview.WebViewUtil;
import com.getpebble.android.widget.CustomToast;
import com.sun.mail.smtp.SMTPMessage;
import java.util.Locale;
import org.json.JSONException;
import org.json.JSONObject;

public class AppStoreFragment extends PblBaseFragment implements IHandleBackPress {
    public static final String TAG = AppStoreFragment.class.getSimpleName();
    private boolean mIsAppInstalling = false;
    private boolean mIsSearchVisible = true;
    private String mPageId;
    private ProgressBar mProgressBar;
    private StoreType mStoreType = StoreType.UNSUPPORTED;
    private WebView mWebView;

    static /* synthetic */ class AnonymousClass3 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult = new int[AppInstallResult.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.SUCCESS.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.ERROR_BANK_FULL.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
        }
    }

    private class AppStoreWebClient extends JsBridgeWebClient {
        private AppStoreWebClient() {
        }

        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            AppStoreFragment.this.mProgressBar.setVisibility(8);
            AppStoreFragment.this.updateDrawerIndicator();
        }

        protected void handleJSBridgeMethods(String methodName, JSONObject methodArgs) {
            if ("addToLocker".equals(methodName)) {
                AppStoreFragment.this.handleAddToLockerRequest(methodArgs, true);
            } else if ("loadAppToDeviceAndLocker".equals(methodName)) {
                AppStoreFragment.this.handleAddToDeviceAndLockerRequest(methodArgs);
            } else if ("setNavBarTitle".equals(methodName)) {
                AppStoreFragment.this.handleSetNavBarTitleRequest(methodArgs);
            } else if ("openURL".equals(methodName)) {
                AppStoreFragment.this.handleOpenUrlRequest(methodArgs);
            } else if ("closeScreen".equals(methodName)) {
                AppStoreFragment.this.handleCloseScreen(methodArgs);
            } else {
                Trace.warning(TAG, "Got unhandled JsBridge method: " + methodName);
            }
        }

        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            AppStoreFragment.this.updateDrawerIndicator();
        }
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    public int getLayoutId() {
        return R.layout.fragment_webview;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        MobileAppBehavior.logScreenOpened("AppStore");
        this.mWebView = (WebView) container.findViewById(R.id.webView);
        this.mWebView.getSettings().setDomStorageEnabled(true);
        this.mProgressBar = (ProgressBar) container.findViewById(R.id.progressbar);
        this.mProgressBar.setVisibility(0);
    }

    public void onStart() {
        super.onStart();
        handleArguments(getArguments());
        configureWebView();
        loadWebView();
    }

    public void onResume() {
        super.onResume();
        if (this.mWebView != null) {
            this.mWebView.resumeTimers();
        }
        updateDrawerIndicator();
        updateFragmentForConnectionStatus();
    }

    public void onLowMemory() {
        super.onLowMemory();
        if (this.mWebView != null) {
            Trace.debug(TAG, "Low Memory: Switching To Software Layer Type");
            this.mWebView.setLayerType(1, null);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        destroyWebView();
        this.mIsSearchVisible = false;
        updateSearchIconVisibility();
    }

    private void destroyWebView() {
        if (this.mWebView != null) {
            this.mWebView.stopLoading();
            this.mWebView.clearAnimation();
            this.mWebView.freeMemory();
            this.mWebView.destroy();
        }
    }

    public void onPause() {
        super.onPause();
        if (this.mWebView != null) {
            this.mWebView.pauseTimers();
        }
    }

    private void updateFragmentForConnectionStatus() {
        Activity activity = getActivity();
        if (activity == null) {
            Trace.error(TAG, "updateFragmentForConnectionStatus(): Activity was null");
        } else if (!HttpUtils.hasInternetConnection(activity) && (activity instanceof MainActivity)) {
            ((MainActivity) activity).switchFragment(new NoConnectivityFragment(), false, false, true);
        }
    }

    public void onStop() {
        super.onStop();
        hideKeyboard();
    }

    private void hideKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService("input_method");
        View view = getActivity().getCurrentFocus();
        if (view != null) {
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 2);
        }
    }

    private void updateDrawerIndicator() {
        boolean enableDrawerIndicator = true;
        if (canGoBack()) {
            enableDrawerIndicator = false;
        }
        Activity activity = getActivity();
        if (activity != null && (activity instanceof MainActivity)) {
            ((MainActivity) activity).setDrawerIndicatorEnabled(enableDrawerIndicator);
        }
    }

    private void updateSearchIconVisibility() {
        Trace.debug(TAG, "Has Search Button = " + this.mIsSearchVisible);
        setHasOptionsMenu(this.mIsSearchVisible);
    }

    @SuppressLint({"NewApi"})
    public void openSearch() {
        JSONObject methodArgs = new JSONObject();
        try {
            methodArgs.put("callbackId", 0);
            methodArgs.put("methodName", "search");
            methodArgs.put("data", new JSONObject());
        } catch (JSONException e) {
            Trace.error(TAG, "openSearchScreen - JSONException:", e);
        }
        String javascriptUrl = String.format("javascript:PebbleBridge.handleRequest(%s);", new Object[]{methodArgs.toString()});
        if (VERSION.SDK_INT >= 19) {
            this.mWebView.evaluateJavascript(javascriptUrl, null);
        } else {
            this.mWebView.loadUrl(javascriptUrl);
        }
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.base_search_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    public void onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menu_search).setVisible(true);
        super.onPrepareOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_search:
                MobileAppBehavior.logSearchTappedEvent();
                Activity activity = getActivity();
                if (activity == null || HttpUtils.hasInternetConnection(activity) || !(activity instanceof MainActivity)) {
                    openSearch();
                    return true;
                }
                ((MainActivity) activity).switchFragment(new NoConnectivityFragment(), false, false, true);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void handleArguments(Bundle arguments) {
        if (arguments != null) {
            this.mStoreType = StoreType.values()[arguments.getInt("extra_store_type", StoreType.UNSUPPORTED.ordinal())];
            this.mPageId = arguments.getString("extra_page_id");
        }
    }

    @SuppressLint({"SetJavaScriptEnabled"})
    private void configureWebView() {
        if (this.mWebView == null) {
            Trace.error(TAG, "configureWebView: Web View was null");
            return;
        }
        this.mWebView.setWebChromeClient(new WebChromeClient());
        this.mWebView.setWebViewClient(new AppStoreWebClient());
        this.mWebView.getSettings().setJavaScriptEnabled(true);
        this.mWebView.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case R.styleable.WalletFragmentStyle_buyButtonHeight /*0*/:
                    case SMTPMessage.RETURN_FULL /*1*/:
                        if (!v.hasFocus()) {
                            v.requestFocus();
                            break;
                        }
                        break;
                }
                return false;
            }
        });
        WebViewUtil.appendPebbleUserAgentStringToWebview(this.mWebView);
    }

    private void loadWebView() {
        if (this.mWebView != null && this.mWebView.getTag() == null) {
            String url = AppStoreConstants.getStoreUrl(this.mStoreType, this.mPageId);
            this.mWebView.setTag(url);
            this.mWebView.loadUrl(url);
        }
    }

    public boolean canGoBack() {
        return this.mWebView != null && this.mWebView.canGoBack();
    }

    public void goBack() {
        if (this.mWebView != null) {
            this.mWebView.goBack();
        }
        updateDrawerIndicator();
    }

    private LockerApp handleAddToLockerRequest(JSONObject methodArgs, boolean sendResult) {
        LockerApp lockerApp = JsBridgeUtil.getWatchAppFromMethodArgs(methodArgs);
        if (lockerApp == null) {
            Trace.error(TAG, "Unable to add to locker; bad data.");
            if (sendResult) {
                CustomToast.show(getActivity(), getString(R.string.app_store_add_locker_failed), getResources().getColor(R.color.default_err_descr_color));
                JsBridgeUtil.appendResultToDataArgs(methodArgs, "added_to_locker", Boolean.valueOf(false));
                JsBridgeUtil.notifyLoadResult(this.mWebView, false, methodArgs);
            }
            return null;
        }
        MobileAppBehavior.logAddToLockerFromWebviewRequested(lockerApp);
        ContentValues contentValues = lockerApp.toContentValues();
        JsBridgeUtil.appendResultToDataArgs(methodArgs, "application_id", lockerApp.getId());
        Activity activity = getActivity();
        if (activity == null) {
            return lockerApp;
        }
        contentValues.put("_needs_add", Integer.valueOf(1));
        activity.getContentResolver().insert(PblContentProviderUtil.getTableUri("locker_apps"), contentValues);
        PebbleApplication.getSyncManager().syncLockerApps();
        if (!sendResult) {
            return lockerApp;
        }
        CustomToast.show(getActivity(), lockerApp.getAppName().toUpperCase(), "", getString(R.string.app_store_add_locker_success), getResources().getColor(R.color.default_orange_color));
        JsBridgeUtil.appendResultToDataArgs(methodArgs, "added_to_locker", Boolean.valueOf(true));
        JsBridgeUtil.notifyLoadResult(this.mWebView, true, methodArgs);
        return lockerApp;
    }

    private void handleAddToDeviceAndLockerRequest(final JSONObject methodArgs) {
        final LockerApp lockerApp = handleAddToLockerRequest(methodArgs, false);
        if (lockerApp == null) {
            Trace.error(TAG, "Unable to add to device, since locker app add failed.");
            sendLoadToDeviceResult(methodArgs, false, false);
            return;
        }
        MobileAppBehavior.logAddToLockerAndInstallFromWebviewRequested(lockerApp);
        PblFrameworkInterface frameworkInterface = PebbleApplication.getFrameworkInterface();
        if (getActivity() != null) {
            PblDevice device = PebbleApplication.getConnectedDevice();
            if (device == null) {
                Trace.error(TAG, "No connected device found!");
                sendLoadToDeviceResult(methodArgs, true, false);
                return;
            }
            String uriStr = lockerApp.getPbwFile();
            if (uriStr == null) {
                Trace.error(TAG, "Unable to find Uri for app");
                sendLoadToDeviceResult(methodArgs, true, false);
            } else if (this.mIsAppInstalling) {
                Trace.error(TAG, "Another app is currently installing");
                sendLoadToDeviceResult(methodArgs, true, false);
                CustomToast.show(getActivity(), lockerApp.getAppName().toUpperCase(), "", getString(R.string.app_store_already_installing), getResources().getColor(R.color.default_orange_color));
            } else {
                this.mIsAppInstalling = true;
                Trace.debug(TAG, "Adding to device: " + device.getName());
                FrameworkEventReceiver.registerFrameworkStateEventListener(new IFrameworkEventListener() {
                    public void onFrameworkStateChanged(FrameworkState newState) {
                        boolean success = false;
                        if (newState.getLastEvent() != null && newState.getLastEvent().equals(EventType.APP_INSTALL_COMPLETE)) {
                            int stringResId;
                            AppStoreFragment.this.mIsAppInstalling = false;
                            AppInstallResult result = AppInstallResult.fromValue(newState.getAppInstallResult());
                            switch (AnonymousClass3.$SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[result.ordinal()]) {
                                case SMTPMessage.RETURN_FULL /*1*/:
                                    stringResId = R.string.app_store_loaded_on_pebble;
                                    break;
                                case SMTPMessage.RETURN_HDRS /*2*/:
                                    stringResId = R.string.app_store_pebble_full_added_to_locker;
                                    break;
                                default:
                                    stringResId = R.string.app_store_failed_to_load;
                                    break;
                            }
                            if (AppStoreFragment.this.getActivity() != null) {
                                CustomToast.show(AppStoreFragment.this.getActivity(), lockerApp.getAppName().toUpperCase(), "", AppStoreFragment.this.getString(stringResId), AppStoreFragment.this.getResources().getColor(R.color.default_orange_color));
                                if (result == AppInstallResult.SUCCESS) {
                                    success = true;
                                }
                                AppStoreFragment.this.sendLoadToDeviceResult(methodArgs, true, success);
                            }
                            FrameworkEventReceiver.unregisterFrameworkStateEventListener(this);
                        }
                    }
                });
                MobileAppBehavior.logAppInstallDetected(lockerApp);
                frameworkInterface.installApp(device, Uri.parse(uriStr), true, false);
            }
        }
    }

    private void sendLoadToDeviceResult(JSONObject methodArgs, boolean lockerResult, boolean loadResult) {
        JsBridgeUtil.appendResultToDataArgs(methodArgs, "added_to_locker", Boolean.valueOf(lockerResult));
        JsBridgeUtil.appendResultToDataArgs(methodArgs, "loaded_on_device", Boolean.valueOf(loadResult));
        JsBridgeUtil.notifyLoadResult(this.mWebView, true, methodArgs);
    }

    private void handleSetNavBarTitleRequest(JSONObject methodArgs) {
        setNavBarTitle(JsBridgeUtil.getTitle(methodArgs), JsBridgeUtil.getShowSearch(methodArgs));
        JsBridgeUtil.notifyLoadResult(this.mWebView, true, methodArgs);
    }

    private void setNavBarTitle(String title, boolean showSearch) {
        if (!TextUtils.isEmpty(title)) {
            setPageTitle(title);
            this.mIsSearchVisible = showSearch;
            updateSearchIconVisibility();
        }
    }

    private void setPageTitle(String title) {
        String upperCaseTitle = title.toUpperCase(Locale.US);
        Activity activity = getActivity();
        if (activity == null) {
            Trace.error(TAG, "setPageTitle: Activity was null");
        } else if (!isAdded()) {
        } else {
            if (activity instanceof MainActivity) {
                ((MainActivity) activity).setWebviewCustomTitle(upperCaseTitle);
            } else {
                activity.setTitle(upperCaseTitle);
            }
        }
    }

    private void handleOpenUrlRequest(JSONObject methodArgs) {
        if (methodArgs != null) {
            try {
                launchUrl(methodArgs.getJSONObject("data").optString("url", null));
                JsBridgeUtil.notifyLoadResult(this.mWebView, true, methodArgs);
            } catch (JSONException e) {
                Trace.error(TAG, "handleOpenUrlRequest - JSONException while parsing:" + methodArgs, e);
            }
        }
    }

    private void launchUrl(String url) {
        Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(url));
        Activity activity = getActivity();
        if (activity == null) {
            Trace.error(TAG, "launchUrl: Activity was null");
        } else {
            activity.startActivity(intent);
        }
    }

    private void handleCloseScreen(JSONObject methodArgs) {
        if (methodArgs != null) {
            Trace.debug(TAG, "handleCloseScreen - methodArgs:" + methodArgs);
            if (canGoBack()) {
                goBack();
            }
            JsBridgeUtil.appendResultToDataArgs(methodArgs, "closed_screen", Boolean.valueOf(true));
            JsBridgeUtil.notifyLoadResult(this.mWebView, true, methodArgs);
        }
    }
}
